<template>
  <view class="star-wrap" :style="`--size:${props.size}px`" >
    <view class="flex al-center" @touchend="onTouch" @touchmove="onTouch" :id="id">
      <image class="star-img" v-for="(item, i) in stars" :key="i" :src="`/assets/imgs/star${i >= index ? '-empty' : ''}.png`" />
    </view>
    <view class="msg" v-if="props.showMsg">{{ getMsg(modelValue) }}</view>
  </view>
</template>
<script setup>
import { View, Image } from '@tarojs/components';
import { createSelectorQuery, getSystemInfoSync } from '@tarojs/taro';
import { computed, onMounted, onUnmounted, reactive, watch } from 'vue';
const props = defineProps({
  size: {
    type: Number,
    default: 20
  },
  showMsg: Boolean
});
const modelValue = defineModel(Number, 10);

const index = computed(() => Math.floor(modelValue.value / 2));

const id = 'star_' + parseInt(Math.random() * 50000);
const stars = new Array(5).fill({});
const state = reactive({
  left: 0,
  ratio: 2,
  width: 750
});
const onTouch = e => {
  const touche = e.changedTouches[0];
  let left = touche.clientX - state.left + props.size * 1.5;
  const currentStar = Math.min(Math.max(parseInt((left / state.width) * 5), 1), 5);
  modelValue.value = currentStar * 2;
};
let unwatch;
onUnmounted(() => {
  unwatch();
});

onMounted(() => {
  unwatch = watch(
    () => props.size,
    () => {
      createSelectorQuery()
        .select('#' + id)
        .boundingClientRect()
        .exec(function (res) {
          if (res[0]) {
            const { left, height, width } = res[0];
            state.left = left;
            state.width = width;
          }
        });
      state.ratio = 750 / getSystemInfoSync().windowWidth;
    },
    {
      immediate: true
    }
  );
});

const starMsg = ['差评', '中评', '好评'];

const getMsg = level => {
  if (level > 7) {
    return starMsg[2];
  }
  if (level > 4) {
    return starMsg[1];
  }
  return starMsg[0];
};
</script>
<style lang="scss">
.star-wrap {
  display: inline-flex;
  align-items: center;
  padding: 15px;
  .star-img {
    width: var(--size);
    height: var(--size);
    margin-bottom: 0;
  }
  .star-img + .star-img {
    margin-left: calc(var(--size) / 2);
  }
  .msg {
    color: var(--color-info);
    margin-left: calc(var(--size) / 1.2);
    font-size: calc(var(--size) / 2);
  }
}
</style>
